package com.fang.security.controller;

import com.fang.security.common.result.JsonResult;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author Bernie
 * @Date 2024/4/23 15:45
 **/
@RestController
@RequestMapping("/index")
public class ExampleController {

    /**
     * 首页
     *
     * @Author Sans
     * @CreateTime 2019/10/2 15:23
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public JsonResult info() {
        // 组装参数
        Map<String, Object> result = new HashMap<>();
        result.put("title", "这里是首页不需要权限和登录拦截");
        return JsonResult.success(result);
    }

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    @PreAuthorize("hasRole('COMMON_USER')")// 不需要前缀
    public JsonResult user() {
        // 组装参数
        Map<String, Object> result = new HashMap<>();
        result.put("title", "这里需要 hasRole('COMMON_USER') 才允许访问");
        return JsonResult.success(result);
    }

    @RequestMapping(value = "/admin", method = RequestMethod.GET)
    @PreAuthorize("hasRole('ADMIN')")// 不需要前缀
    public JsonResult admin() {
        // 组装参数
        Map<String, Object> result = new HashMap<>();
        result.put("title", "这里需要hasRole('ADMIN')才允许访问");
        return JsonResult.success(result);
    }

    @RequestMapping(value = "/anyRole", method = RequestMethod.GET)
    @PreAuthorize("hasAnyRole('ADMIN','COMMON_USER')")// 不需要前缀
    public JsonResult anyRole() {
        // 组装参数
        Map<String, Object> result = new HashMap<>();
        result.put("title", "这里需要 hasAnyRole('ADMIN','COMMON_USER') 才允许访问");
        return JsonResult.success(result);
    }

    @RequestMapping(value = "/role_auth", method = RequestMethod.GET)
    @PreAuthorize("hasRole('COMMON_USER') AND hasAuthority('query_user')")
    public JsonResult role_auth() {
        // 组装参数
        Map<String, Object> result = new HashMap<>();
        result.put("title", "这里需要 hasRole('COMMON_USER') AND hasAuthority('query_user') 才允许访问");
        return JsonResult.success(result);
    }

    /**
     * @Author Bernie
     * @Description hasPermission方法在需要复杂且细粒度的权限控制时使用，hasAuthority() 和 hasRole() 等方法已经够用，只需给予足够的权限即可，而且不需要重写
     * @Date 15:37 2024/5/9
     * @return: com.fang.security.common.result.JsonResult
     **/
    @RequestMapping(value = "/role_auth2", method = RequestMethod.GET)
    @PreAuthorize("hasRole('COMMON_USER') AND hasPermission('role_auth2', 'query_user')")
    public JsonResult role_auth2() {
        // 组装参数
        Map<String, Object> result = new HashMap<>();
        result.put("title", "这里需要 hasRole('COMMON_USER') AND hasPermission('query_user') 才允许访问");
        return JsonResult.success(result);
    }

}
